import React, { Component } from "react";
import $ from "jquery";
import "../VideoList/VideoList.css";
import config from '../config.js'
import play from "../images/play.png";
import Uploadfiles from "../popup/Uploadfiles/Uploadfiles.js"
import {withRouter} from "react-router-dom";
import VideoListTop from "../VideoListTop/VideoListTop";
import Reupload from "../popup/reupload/reupload.js"
import VideoListTopButton from "../VideoListTopButton/VideoListTopButton";
import VideoList from "../VideoList/VideoList";
import Paging from "../Paging/Paging";
import DeleteConfirm from "../popup/DeleteConfirm/DeleteConfirm";



var _this;
class Home extends Component {
    constructor(){
        super()
        this.state={
            videoshow:false,
            uploadFilelistActive:false,delVideoPopupActive:false,videoPlayMask:false,mask:false,
            fileList:{length:0},
            videoList:[],
            index:1,
            delvid:-1,
            num:'',
            arr:[],
            errorarr:[]
        }
    }

    closeDelVidoPopup(){
        this.setState({
            delVideoPopupActive: false
        });
    }

    delVideoSure() {
        var arg = {
          uid: _this.state.info.uid,
          token: _this.state.info.token,
          vid: _this.state.delvid
        };
    
        var list = _this.state.videoList;
        var index = _this.state.index;
    
        if (list.length == 1) {
          index = index - 1;
          _this.setState({ index: index });
        }
    
        config.sendRequest(config.url.delInfo, arg, function(res) {
            _this.closeDelVidoPopup();
            _this.refresh(index);
        });
    }

    closeMask(){
        console.log("close mask")
        this.setState({
            mask:false
        })
    }

    openMask(){
        this.setState({
            mask:true
        })
    }

    delInfo(e){
        _this.setState({
            delvid:e.target.id,
            delVideoPopupActive:true
        })
    }
    
    setInfoToState(info){
        this.setState({
            info:info
        })
    }

    pushIndex(info){
        if(!info) this.props.history.push('/');
    }

    initComponent(){
        var info=config.getInfo()
        this.pushIndex(info)
        this.setInfoToState(info)
        this.refresh(this.state.index)
    }

    componentWillMount(){
        this.initComponent();
    }

    refresh(index) {
        var info = JSON.parse(sessionStorage.getItem("info"));
        var arg = {uid: info.uid,token: info.token, p:index};


        console.log('refresh',arg)
    
        config.sendRequest(config.url.h5Video, arg, function(res) {
          if (res.status == 200) {
            var videoList = res.data.rs;
            _this.setState({
              videoList: videoList,
              num: res.data.nums
            });
            $(".progress").width("0%");
            _this.setarr(res.data.nums);
          }
        });
    }

    setarr(num){
       var page=Math.ceil(parseInt(num)/4)
       var arr=[]
       if(page<=5){
            for(var i=1;i<=page;i++){
                arr.push(i)
            }
       }
       if(page>=6){
           arr=[1,2,3,4,page]
       }
       this.setState({
           arr:arr
       })
    }
  
    uploadfile(){
        this.setState({
          loadstate:true  
        })
    }

    closeDelConfirm(){
        _this.setState({
            delVideoPopupActive:false
        })
    }

    closeUploadFilesPOPUP(){
        this.setState({
            uploadFilelistActive:false,
            fileList:{length:0}//清空列表
        })
        sessionStorage.removeItem('vname');
    }
    onChildChanged(res,state){
         $(".progress").width(res+"%");
         if(state){
             this.setState({
                 loadstate:false
             })
             this.refresh(1)
         }
    }

   
    hideMask(){
        this.setState({
            videoshow:false
        })
    }
    nextrefresh(index){
         var info=JSON.parse(sessionStorage.getItem("info"));
        var videoListUrl=config.url.h5Video+'?jsondata={"uid":"'+info.uid+'","token":"'+info.token+'","p":'+index+'}';
        $.get(videoListUrl,res=>{
            res=JSON.parse(res);
            //  console.log(res)
            if(res.status==200){
                var videoList=res.data.rs;
                this.setState({
                    videoList:videoList,
                })
            }
        })
    }

    clearFileList(){
        console.log("clearFileList")
        this.setState({
            fileList:{length:0}
        })
    }
    clearOne(index){
        var tempList=this.state.fileList;

        delObjIndex(tempList,index)

        function delObjIndex(obj,index){
            for(var i in obj){
                if(index==i){
                    delete obj[index]
                }
            }
        }
        tempList.length--;

     

        console.log("templist 2222222222222222222")
        console.log(tempList)

        function sortLikeArray(likeArray){
            var sortedArray;
            var tempData=[];
            var sortedArray=[];
            var len=likeArray.length;

            for(var i in likeArray){
                if(i=='length'){
                    break;
                }
                tempData.push(likeArray[i])
            }

            for(var i =0;i<len;i++){
                sortedArray.push(tempData[i])
            }

            return sortedArray;
        }

        var sortedArray=sortLikeArray(tempList)
        console.log("sorted array")
        console.log(sortedArray)

        // console.log(Array.prototype.slice.call(tempList))

        function arrToLikeArray(arr){
            var likeArray={length:0};

           for(var i =0;i<arr.length;i++){
            likeArray[i]=arr[i];
            likeArray.length++;
           }

            return likeArray;
        }

        tempList=arrToLikeArray(sortedArray)

        this.setState({
            fileList:tempList
        })
    }

  
    changeFilelist(fileList){
        function pushToObj(tempFiles,srcFiles){
            var index=tempFiles.length || 0;
    
            for(let v of srcFiles){
                tempFiles[index]=v;
                index++;
            }
            tempFiles.length=index;
    
           return tempFiles;
        }
        console.log("push前-------")
        console.log(this.state.fileList)
    
        var newFileList = pushToObj(this.state.fileList,fileList)
    
       console.log("newFileList")
        console.log(newFileList)
    
        this.setState({
            uploadFilelistActive:true,
            fileList:newFileList
        })
    }


    selectFiles(e){
        _this.changeFilelist(e.target.files)
    }
    showDelPopup(){
        console.log("show del popup")
        _this.setState({
            delVideoPopupActive:true
        })
    }

    seterror(e){
        this.setState({
            errorarr:e
        })
    }

    clearReOne(index){
        var errorarr=this.state.errorarr;
        for(let i in errorarr){
            if(index==i){
                errorarr.splice(i,1)
            }
        }
        this.setState({
            errorarr:errorarr
        })
    }

    closeReUploadFiles(){
        this.setState({
            mask:false,
            errorarr:[]//清空列表
        })       
    }
    reuploadfile(){
        var errorarr=this.state.errorarr;
        var info = JSON.parse(sessionStorage.getItem("info"));
        this.setState({mask:false})
        for(let i=errorarr.length-1;i>=0;i--){
             var a = {
              uid: info.uid,
              token: info.token,
              vid: errorarr[i].vid,
              name: errorarr[i].name
            };

            $.post(config.url.upload, a, function(r) {
                console.log(i)
                errorarr.splice(i,1)

                _this.setState({
                   errorarr:errorarr 
                })

                _this.refresh(1)
            })
        }
    }
    resetreupload(e){
        this.setState({errorarr:e})
    }

    //分页
    goafter() {
        var arr = this.state.arr;
        var page = Math.ceil(parseInt(this.state.num) / 4);
        var index = parseInt(this.state.index) + 1;
        if (index > page) {
        return;
        }
        //超过6页
        if (page > 6) {
            if (arr[1] == 2 && index < 3) {
            } else {
                if (arr[3] < page - 1) {
                for (var i = 1; i < 4; i++) {
                    arr[i] = arr[i] + 1;
                }
                }
            }
        }
        this.setState({
        arr: arr,
        index: index
        });
        this.nextrefresh(index);
    }

    gobefore() {
        var arr = this.state.arr;
        var page = Math.ceil(parseInt(this.state.num) / 4);
        var index = parseInt(this.state.index) - 1;
        if (index == 0) {
        return;
        }
        if (index == 1) {
            this.setState({
                index: index
            });
            this.nextrefresh(index);
            return;
        }
        this.setState({
        index: index
        });
        this.nextrefresh(index);
        if (page >= 6) {
            if (arr[1] == 2 || (arr[3] == page - 1 && index == page - 1)) {
                return;
            }
            for (var i = 1; i < 4; i++) {
                arr[i] = arr[i] - 1;
            }
        }
        this.setState({
        arr: arr
        });
    }
    changearr(e) {
        var index = parseInt(e.target.id);
        var preindex = parseInt(this.state.index);
        var a;
        if (index == preindex) {
        a = 0;
        }
        if (index > preindex) {
        a = 1;
        }
        if (index < preindex) {
        a = -1;
        }
        var page = Math.ceil(parseInt(this.state.num) / 4);
        var arr = this.state.arr;
        if (page <= 5) {
        this.nextrefresh(index);
        this.setState({
            arr: arr,
            index: index
        });
        }
        if (page >= 6) {
        if (index < page) {
            if (
            (index == 2 && arr[1] == 2) ||
            (arr[3] == page - 1 && index == page - 1) ||
            (arr[2] == page - 2 && index == page - 2)
            ) {
            } else {
            for (var i = 1; i < 4; i++) {
                arr[i] = arr[i] + a;
            }
            }
        } else {
            arr = [1, page - 3, page - 2, page - 1, page];
        }
        if (index == 1) {
            arr = [1, 2, 3, 4, page];
        }
        this.nextrefresh(index);
        this.setState({
            arr: arr,
            index: index
        });
        }
    }


  render() {
    _this=this;
    var reupload=this.state.errorarr.length>0?true:false
    
    return (
      <div className="videolist-wrap">
        <div className={this.state.uploadFilelistActive || this.state.delVideoPopupActive || this.state.videoPlayMask || this.state.mask ? 'show mask' : 'hide mask' }></div>
        <DeleteConfirm delVideoPopupActive={this.state.delVideoPopupActive} closeDelConfirm={this.closeDelConfirm} delVideoSure={this.delVideoSure}/>
        <div className={this.state.videoPlayMask ?"video-play-mask show":"video-play-mask"}></div>
        <div className="progress"></div>
        <div>
            {/* <div  className={this.state.confirmdel?'show Total':'hide'}></div> */}
            <div className={this.state.confirmdel?'mask':''} onClick={()=>this.cancel()}></div>
            
        </div>
        <VideoListTop>
            <VideoListTopButton history={this.props.history} selectFiles={this.selectFiles}/> 
        </VideoListTop>

        <Uploadfiles 
            clearOne={this.clearOne.bind(this)} 
            callbackParent={this.onChildChanged.bind(this)} 
            onChange={this.selectFiles} 
            one={this.clearFileList.bind(this)} 
            closeUploadFilesPOPUP={this.closeUploadFilesPOPUP.bind(this)}  
            fileList={Array.prototype.slice.call(this.state.fileList)}
            uploadFilelistActive={this.state.uploadFilelistActive} mask={this.state.mask}
            closeMask={this.closeMask.bind(this)}
            errorarr={this.seterror.bind(this)}
            />
        <Reupload errorarr={this.state.errorarr} clearReOne={this.clearReOne.bind(this)} closeReUploadFiles={this.closeReUploadFiles.bind(this)} reuploadfile={this.reuploadfile.bind(this)} reset={this.resetreupload.bind(this)}/>
        <VideoList videoList={this.state.videoList} delInfo={this.delInfo} openMask={this.openMask.bind(this)} closeMask={this.closeMask.bind(this)} num={this.state.num} >
         <Paging num={this.state.num} arr={this.state.arr} index={this.state.index} goafter={this.goafter.bind(this)} gobefore={this.gobefore.bind(this)} changearr={this.changearr.bind(this)}/>
         </VideoList>
         

      </div>
    );
  }
}

export default withRouter(Home)